<template>
	<view class="details">
		<image class="main-image" :src="details.img" mode="aspectFill"></image>
		<view class="name">{{details.name}}</view>
		<view class="content-wrapper">
			<template v-if="details.type === '4'">
				<view class="distance-info">
					<view class="location-wrapper">
						<image class="location-icon" src="/static/icon/glicondibiao.png"></image>
						<text>你当前距离{{details.name}}有{{dis}}km</text>
					</view>
					<button class="nav-btn" @tap="setLine">到{{details.name}}去</button>
				</view>
			</template>
			<!-- <button class="nav-btn collect-btn" @tap="collectPlace">
				<uni-icons type="star" size="14" color="white"></uni-icons> -->
				<!-- <text></text> -->
				<view class="fav">
					<uni-fav :checked="hasFav" class="nav-btn collect-btn" @click="toggleFavorite" :disabled="hasFav">
						{{ hasFav ? '已收藏' : '收藏' }}
					</uni-fav>
				</view>
			<!-- </button> -->
		</view>
		<view class="intro-section">
			<view class="intro-title">介绍</view>
			<view class="intro-content">{{details.intro}}</view>
		</view>
	</view>
</template>

<script setup>
	import {
		onLoad
	} from "@dcloudio/uni-app"
	import {
		ref
	} from 'vue'
	import {
		CONFIG,
		LeanCloudHeader
	} from "../../utils/config"
	import {
		getMapDistance
	} from "/utils/tools.js"
	import {
		userStore
	} from "../../store/userStrore"
	const store = userStore()

	let details = ref({})
	let dis = ref()
	let hasFav = ref(false)

	onLoad((data) => {
		//进详情直接去登录页面
		// if (!store.isLogin) {
		// 	uni.navigateTo({
		// 		url: '/pages/login/login'
		// 	});
		// 	return;
		// }

		const id = data.id
		getDetails(id)
	})

	async function getDetails(id) {
		try {
			let res = await uni.$get(`${CONFIG.leanCloud_url}/1.1/classes/senicltem/${id}`)
			if (res.statusCode === 200) {
				details.value = res.data
				checkFavoriteStatus(details.value.name)
			}
		} catch (error) {
			console.error("获取详情失败：", error)
		}
	}

	async function checkFavoriteStatus(name) {
		try {
			let res = await uni.$get(`${CONFIG.favXianObj}?where={"favName":"${name}","username":"${store.userinfo.username}"}`, {
				headers: LeanCloudHeader(store.userinfo.sessionToken)
			})
			if (res.statusCode === 200 && res.data.results.length > 0) {
				hasFav.value = true
			}
		} catch (error) {
			// console.error("检查收藏状态失败：", error)
		}
	}

	function toggleFavorite() {
		if (!store.isLogin) {
			uni.navigateTo({
				url: '/pages/login/login'
			})
			return
		}

		if (!hasFav.value) {
			addFavorite(details.value)
		}
	}

	function addFavorite(item) {
		const favoriteData = {
			username: store.userinfo.username,
			typeId: item.img,
			favPic: item.intro,
			favName: item.name,
			favObjId: item.id
		};

		const sessionToken = store.userinfo.sessionToken;
		const headers = LeanCloudHeader(sessionToken);

			uni.request({
				url: CONFIG.favXianObj,
				method: 'POST',
				header: headers,
				data: favoriteData,
				success: (res) => {
					if (res.objectId !== null) {
						uni.showToast({
							title: '收藏成功',
							icon: 'success'
						});
						hasFav.value = true;
					} else {
						uni.showToast({
							title: '收藏失败...',
							icon: 'error'
						});
					}
				},
				fail: (err) => {
					console.error('请求失败:', err);
					uni.showToast({
						title: '请求失败',
						icon: 'error'
					});
				}
			});
	}

	function removeFavorite(itemId) {
		uni.request({
			// url: `${CONFIG.favXianObj}?where={"userId":"${store.userinfo.username}","itemId":"${itemId}"}`,
			// method: 'DELETE',
			header: LeanCloudHeader(store.userinfo.sessionToken),
			success: (res) => {
				if (res.objectId !==null) {
						title: '已收藏成功'
					
				} 
			},
			fail: (err) => {
				console.error('请求失败:', err)
				uni.showToast({
					title: '请求失败',
					icon: 'error'
				})
			}
		})
	}

	async function setLine() {
		try {
			await new Promise((resolve, reject) => {
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						store.setPos(res.longitude, res.latitude)
						resolve()
					},
					fail: reject
				})
			})

			uni.navigateTo({
				url: `/pages/playWebView/playWebView?slat=${store.currentPos.latitude}&slon=${store.currentPos.longitude}&elat=${details.value.lat}&elon=${details.value.lon}&name=${details.value.name}`
			})
		} catch (error) {
			console.error('获取位置失败：', error)
			uni.showToast({
				title: '获取位置失败，请检查定位权限',
				icon: 'none'
			})
		}
	}

	function collectPlace() {
		if (store.isLogin) {
			uni.$post("https://julwaqq0.lc-cn-n1-shared.com/1.1/classes/favXianObj", res)
				.then(res2 => {
					console.log(res2)
					if (res2.statusCode == 400) {
						uni.showToast({
							title: "用户名或密码错误..."
						})
					} else if (res2.statusCode == 200) {
						store.addSouCang(details.img, details.name, details.type, details.intro)
						uni.navigateTo({
							url: '/pages/collect/collect'
						})
					}
				}).catch(err => {
					// 失败
					console.log(err)
				})
		} else {

			uni.navigateTo({
				url: '/pages/login/login'
			})
		}


	}
</script>

<style>
	.details {
		padding: 10px;
	}

	.main-image {
		width: 100%;
		height: 240px;
		/* 增加图片高度 */
	}

	.name {
		font-size: 18px;
		font-weight: bold;
		margin: 10px 0;
	}

	.content-wrapper {
		padding: 0 10px;
	}

	.distance-info {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 10px;
	}

	.location-icon {
		width: 20px;
		height: 20px;
	}

	.nav-btn {
		background-color: #ff2756;
		color: white;
		padding: 0 10px;
		min-width: 60px;
		font-size: 14px;
		line-height: 2;
		border-radius: 4px;
		margin: 0;
		width: fit-content;
	}

	.intro-section {
		margin-top: 10px;
	}

	.intro-title {
		font-size: 16px;
		font-weight: bold;
		margin-bottom: 5px;
	}

	.intro-content {
		font-size: 16px;
		color: #666;
		line-height: 1.6;
	}

	.location-wrapper {
		display: flex;
		align-items: center;
		gap: 4px;
		/* 减小图标和文字的间距 */
	}

	.collect-btn {
		display: flex;
		align-items: center;
		gap: 4px;
		margin-left: auto;
		/* 确保靠右对齐 */
	}

	.collect-btn uni-icons {
		margin-top: 1px;
		/* 微调图标位置 */
	}
</style>